var Movie = require("../models/movie");
var Catgory = require("../models/catgory");

// 首页
exports.index = function (req, res) {
    Catgory
    .find({})
    .populate({path:'movies',options:{limit:5}})
    .exec(function (err, catgories){
        if (err) {
            console.log(err);
        }
        res.render("index", {
            title: "首页",
            catgories: catgories
        });
    })
}

// 搜索
exports.search = function (req, res) {
    var catId = req.query.cat;
    var page = parseInt(req.query.p, 10) || 1;
    var count = 2; // 每页多少条数据
    var index = (page - 1) * count;
    var q = req.query.q;

    if(catId){
        Catgory
            .find({_id: catId})
            .populate({
                path: 'movies',
                select: 'title poster',
                // options: { limit: count, skip: index }
            })
            .exec(function (err, catgories){
                if (err) {
                    console.log(err);
                }
                var catgory = catgories[0] || {};
                var movies = catgory.movies || [];
                var results = movies.slice(index, index + count);

                res.render("results", {
                    title: "查询结果",
                    currentPage: page,
                    query:'cat=' + catId,
                    totalPage: Math.ceil(movies.length / count),
                    keyword: catgory.name,
                    movies: results
                });
            })
    }else if(q){
        Movie
            .find({ title: new RegExp(q +'.*','i') })
            .exec(function (err, movies) {  
                if (err) {
                    console.log(err);
                }
                var results = movies.slice(index, index + count)
                
                res.render("results", {
                    title: "查询结果",
                    currentPage: page,
                    query:'q=' + q,
                    totalPage: Math.ceil(movies.length / count),
                    keyword: q,
                    movies: results
                });
            })
    }
}
